﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;

namespace CommonHelper
{
    public class HexHelper
    {
        /// <summary>
        /// 将字节数组转化为字符串
        /// </summary>
        /// <param name="bytes">需要转换为字符串的数组</param>
        /// <param name="Split">间隔符号</param>
        /// <param name="StringFormat">转换的格式，默认X2,即16进制</param>
        /// <returns>转换后的结果</returns>
        public static string ByteArrayToString(IEnumerable<byte> bytes, string Split = " ", string StringFormat = "X2")
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in bytes)
            {
                sb.Append(item.ToString(StringFormat));
                sb.Append(Split);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 将16进制字符串转化为字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <param name="Split"></param>
        /// <returns></returns>
        public static byte[] StringToByteArray(string hexString, string Split = " ")
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            //验证是否为正确的16进制字符串；
            var hexStringTem = hexString.Replace(Split, "");
            var MatchResult = Regex.Match(hexStringTem, "[^0-9a-fA-F]");
            stopwatch.Stop();
            if (MatchResult.Success || (hexStringTem.Length % 2 != 0))
            {
                throw new Exception("非法的二进制字符串，除分割字符串外字符串长度必须为偶数且要转换的字符串中不能包含0-9,a-f,A-F字符之外的字符,");
            }


            byte[] byteArray = new byte[hexString.Length / 2];
            for (int i = 0; i < byteArray.Length; i++)
            {
                byteArray[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
            return byteArray;
        }
    }
}
